package com.wanmait.recycle.filter;

import java.io.IOException;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class SaveLocalFilter
 */
@WebFilter(dispatcherTypes = {
		DispatcherType.REQUEST, 
		DispatcherType.INCLUDE
}
, urlPatterns = { "*.jsp" })
public class SaveLocalFilter implements Filter {

    /**
     * Default constructor. 
     */
    public SaveLocalFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession();
		
		String ss =  req.getServletPath().substring(0, req.getServletPath().length()-4);
		
		if("/WEB-INF/web/userLogin/login".equals(ss)) {
			String referer = req.getHeader("referer");
			
			String lastUrl = referer.substring(27);
			
			String st = lastUrl.replace("?", ":");
			String[] s = st.split(":");
			
			if(!"/web/userLogin/login".equals(s[0])) {
				if(!"/web/userLogin/login.html".equals(lastUrl)) {
					String url =null;
					if(lastUrl.length()>14) {
						url = lastUrl.substring(0, 14);
						
					}
					 
					 if("/web/userLogin".equals(url)) {
						 lastUrl="/index";
					 }
					
					 session.setAttribute("lastUrl", lastUrl);
				}				
			 }
		}
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
